package org.agile2soft.nexoma.tapestry.encoder;

import java.util.List;

import org.agile2soft.nexoma.controller.UserRequestController;
import org.agile2soft.nexoma.entity.UserRequest;
import org.agile2soft.nexoma.entity.UserRequestId;
import org.apache.tapestry5.EventContext;
import org.apache.tapestry5.ValueEncoder;
import org.hibernate.SessionFactory;

import br.com.arsmachina.tapestrycrud.encoder.Encoder;
import br.com.arsmachina.tapestrycrud.hibernate.encoder.HibernatePrimaryKeyEncoder;

public class UserRequestEncoder
      extends HibernatePrimaryKeyEncoder<UserRequest,UserRequestId>
      implements Encoder<UserRequest,UserRequestId>{

    public UserRequestEncoder(
            Class<UserRequest> entityClass,
            UserRequestController controller,
            SessionFactory sessionFactory) {
        super(entityClass, controller, sessionFactory);
    }
//    public UserRequestEncoder(
//            Class<UserRequest> entityClass,
//            UserRequestController controller,
//            SessionFactory sessionFactory,
//            PrimaryKeyTypeService primaryKeyTypeService) {
//        super(entityClass, controller, sessionFactory, primaryKeyTypeService);
//    }
    public Class<UserRequestId> getKeyType() {
        return UserRequestId.class;
    }

    public void prepareForKeys(List<UserRequestId> keys) {

    }

    public UserRequestId toKey(UserRequest value) {
        return value.getId();
    }

    public UserRequest toValue(UserRequestId key) {
        return getController().findById(key);
    }

    public String toClient(UserRequest value) {
        return String.format("%s-%s",value.getId().getDocumentNumber(),value.getId().getId());
    }

    public UserRequest toValue(String clientValue) {
        String[] id = clientValue.split("-");
        return getController().findById(new UserRequestId(id[0],new Integer(id[1])));
    }

    public ValueEncoder<UserRequest> create(Class<UserRequest> type) {
        return this;
    }

    public Object toActivationContext(UserRequest arg0) {
        return null;
    }

    public UserRequest toObject(EventContext eventContext) {
        UserRequestId userRequestId = new UserRequestId();
        userRequestId.setId(eventContext.get(Integer.class, 0));
        userRequestId.setDocumentNumber(eventContext.get(String.class, 0));
        return getController().findById(userRequestId);
    }

    public String toLabel(UserRequest arg0) {
        return String.format("User.Request %s",arg0.getId().getId());
    }



}
